import request from '~/api/request';
const app = getApp()

const maxSearchNPS = 2000.0
Page({
  data: {
    nps : {
      maxSearchNPS: maxSearchNPS,
      maxNPS: maxSearchNPS,
      minNPS: 0.0,
      minNPSStr: "0.0",
      maxNPSStr: maxSearchNPS / 100.0,
      status: [false, false] // status[0] -- if minNPS is set, status[1] -- if maxNPS is set.
    },
    historyWords: [],
    popularWords: [],
    searchValue: '',
    dialog: {
      title: '确认删除当前历史记录',
      showCancelButton: true,
      message: '',
    },
    dialogShow: false,
  },

  deleteType: 0,
  deleteIndex: '',

  onShow() {
    this.queryHistory();
    this.queryPopular();
  },

  /**
   * 查询历史记录
   * @returns {Promise<void>}
   */
  async queryHistory() {
    // TODO: Search history from web.
  },

  /**
   * 查询热门搜索
   * @returns {Promise<void>}
   */
  async queryPopular() {
    this.setData({
      popularWords: ['bbid 7880', '霍元甲', 'Megalovania']
    })
  },

  setHistoryWords(searchValue) {
    if (!searchValue) return;

    const {
      historyWords
    } = this.data;
    const index = historyWords.indexOf(searchValue);

    if (index !== -1) {
      historyWords.splice(index, 1);
    }
    historyWords.unshift(searchValue);

    this.setData({
      searchValue,
      historyWords,
    });
    // if (searchValue) {
    //     wx.navigateTo({
    //         url: `/pages/goods/result/index?searchValue=${searchValue}`,
    //     });
    // }
  },

  /**
   * 清空历史记录的再次确认框
   * 后期可能需要增加一个向后端请求的接口
   * @returns {Promise<void>}
   */
  confirm() {
    const {
      historyWords
    } = this.data;
    const {
      deleteType,
      deleteIndex
    } = this;

    if (deleteType === 0) {
      historyWords.splice(deleteIndex, 1);
      this.setData({
        historyWords,
        dialogShow: false,
      });
    } else {
      this.setData({
        historyWords: [],
        dialogShow: false
      });
    }
  },

  /**
   * 取消清空历史记录
   * @returns {Promise<void>}
   */
  close() {
    this.setData({
      dialogShow: false
    });
  },

  /**
   * 点击清空历史记录
   * @returns {Promise<void>}
   */
  handleClearHistory() {
    const {
      dialog
    } = this.data;
    this.deleteType = 1;
    this.setData({
      dialog: {
        ...dialog,
        message: '确认删除所有历史记录',
      },
      dialogShow: true,
    });
  },

  deleteCurr(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      dialog
    } = this.data;
    this.deleteIndex = index;
    this.deleteType = 0;
    this.setData({
      dialog: {
        ...dialog,
        message: '确认删除当前历史记录',
      },
      dialogShow: true,
    });
  },

  /**
   * 点击关键词跳转搜索
   * 后期需要增加跳转和后端请求接口
   * @returns {Promise<void>}
   */
  handleHistoryTap(e) {
    const {
      historyWords
    } = this.data;
    const {
      index
    } = e.currentTarget.dataset;
    const searchValue = historyWords[index || 0] || '';

    this.setHistoryWords(searchValue);

    this.jumpTo(searchValue)
  },

  handlePopularTap(e) {
    const {
      popularWords
    } = this.data;
    const {
      index
    } = e.currentTarget.dataset;
    const searchValue = popularWords[index || 0] || '';

    this.setHistoryWords(searchValue);
    this.jumpTo(searchValue);
  },
  onSearchChange(e){
    this.setData({
      searchValue: e.detail.value
    })
  },
  resetNPS(){
    this.setData({
      "nps.minNPS" : 0.0,
      "nps.maxNPS": maxSearchNPS,
      "nps.minNPSStr": "0.0",
      "nps.maxNPSStr": maxSearchNPS / 100.0,
      "nps.status": [false, false]
    })
  },
  /**
   * 提交搜索框内容
   * 后期需要增加跳转和后端请求接口
   * @returns {Promise<void>}
   */
  handleSubmit(e) {
    const {
      value
    } = e.detail;
    if (value.length === 0) return;

    this.setHistoryWords(value);

    this.jumpTo(value);
  },
  onButtonTap(){
    this.jumpTo(this.data.searchValue)
  },
  jumpTo(value){
    console.log("Value:" + value)
    const prefix = "bbid "
    wx.showLoading({
      title: '加载中...',
      mask: true
    })

    if (value.startsWith(prefix)) { // Search by ID
      const id = value.slice(prefix.length).trim();
      wx.cloud.callFunction({
        name: 'getMap',
        data: {
          id: id
        },
        success(res){
          wx.hideLoading()
          console.log("Got map" , res.result.data)
          wx.navigateTo({
            url: '/pages/song/index',
            success(navigateRes){
              navigateRes.eventChannel.emit('acceptSongItem', res.result.data)
            }
          })
        },
        fail(err){
          console.log("Call remote failed", err)
        }
      })
    } else // Search by Name
    {
      app.globalData.queryInfo.q = value
      app.globalData.queryInfo.nps = {
        status: this.data.nps.status,
        min: this.data.nps.minNPS / 100.0,
        max: this.data.nps.maxNPS / 100.0
      }
      app.globalData.needRefresh = true
      
      wx.switchTab({
        url: '/pages/home/index',
      })
    }
  },
  /**
   * 点击取消回到主页
   * @returns {Promise<void>}
   */
  actionHandle() {
    this.setData({
      searchValue: '',
    });
    wx.switchTab({
      url: '/pages/home/index'
    });
  },
  onMinChange(e){
    const newMin = Number(e.detail.value);
    let curStatus = this.data.nps.status;
    curStatus[0] = true;
    const newMax = Math.max(newMin, this.data.nps.maxNPS)
    if(newMax != this.data.nps.maxNPS)
      curStatus[1] = true;

    this.setNPSSelecter(newMin, newMax)
    this.setData({
      "nps.status": curStatus
    });
  },
  onMaxChange(e){
    const newMax = Number(e.detail.value)
    let curStatus = this.data.nps.status;
    curStatus[1] = true
    const newMin = Math.min(this.data.nps.minNPS, newMax)
    if(newMin != this.data.nps.minNPS){
      curStatus[0] = true
    }
    this.setNPSSelecter(newMin, newMax)
    this.setData({
      "nps.status": this.data.nps.status
    });
  },
  setNPSSelecter(min, max){
    this.setData({
      "nps.minNPS": min,
      "nps.maxNPS": max,
      "nps.minNPSStr": min / 100.0,
      "nps.maxNPSStr": max / 100.0
    })
  }
});